//
//  Constants.m
//  NEWMOHO
//
//  Created by rimi on 2017/8/15.
//  Copyright © 2017年 yangkai. All rights reserved.
//

#import "Constants.h"
#import "AppDelegate.h"
#import "CommonCrypto/CommonDigest.h"
#import <MBProgressHUD.h>

@implementation Constants

+(void)showAAlertMessage:(NSString *)msg title:(NSString *)title buttonTexts:(NSArray *)arrTexts buttonAction:(void (^)(int buttonIndex))buttonAction{
    
    if (arrTexts && arrTexts.count) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:title ? title : @"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        int index = 0;
        for (NSString * strText in arrTexts) {
            [alert addAction:[UIAlertAction actionWithTitle:strText ? strText :@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (buttonAction) {
                    buttonAction(index);
                }
            }]];
            index++;
        }
        [[self keyController] presentViewController:alert animated:true completion:nil];
    }
    
}
+(UIViewController *)keyController{
    UIViewController * keyController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    do{
        if (keyController.presentedViewController) {
            keyController = keyController.presentedViewController;
        }else{
            break;
        }
    }while(keyController.presentedViewController);
    return keyController;
}

+ (NSString *)appVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version       = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}

//判断字符是否为空
+(BOOL)isTextEmpty:(NSString *)str{
    if (str == nil || (id)str == [NSNull null]) {
        return YES;
    }else{
        if (![str respondsToSelector:@selector(length)]) {
            return YES;
        }
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([str length]) {
            return NO;
        }
    }
    return YES;
}

//计算字节长度 中文两个字节
+ (NSUInteger)textLength: (NSString *) text{
    
    NSUInteger asciiLength = 0;
    
    for (NSUInteger i = 0; i < text.length; i++) {
        
        
        unichar uc = [text characterAtIndex: i];
        
        asciiLength += isascii(uc) ? 1 : 2;
    }
    
    NSUInteger unicodeLength = asciiLength;
    
    return unicodeLength;
    
}
+ (NSString *)subStringByByteWithIndex:(NSInteger)index contentText:(NSString *)text{
    
    NSInteger sum = 0;
    
    NSString *subStr = [[NSString alloc] init];
    
    for(int i = 0; i<[text length]; i++){
        
        unichar strChar = [text characterAtIndex:i];
        
        if(strChar < 256){
            sum += 1;
        }
        else {
            sum += 2;
        }
        if (sum > index) {
            
            subStr = [text substringToIndex:i];
            return subStr;
        }
    }
    
    return subStr;
}

+ (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}

+(NSString *)md5:(NSString *)inPutText
{
    const char *cStr = [inPutText UTF8String];//转换成utf-8
    
    unsigned char result[16];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    
    CC_MD5( cStr, strlen(cStr), result);
    
    return [NSString stringWithFormat:
            
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            
            result[0], result[1], result[2], result[3],
            
            result[4], result[5], result[6], result[7],
            
            result[8], result[9], result[10], result[11],
            
            result[12], result[13], result[14], result[15]
            
            ];
}

+ (NSString *)md5Douho:(NSString *)inPutText
{
    NSString *md5String = [Constants md5:inPutText];
    NSMutableString *resultString = [NSMutableString string];
    
    for (int x = 0; x<md5String.length; x++)
    {
        int asciiCode = [md5String characterAtIndex:x]; //65
        NSString *appendString = [NSString stringWithFormat:@"%c",asciiCode+(x > md5String.length - x ? 1 : -1)];
        if ( x % 2 == 0)
        {
            [resultString appendString:appendString];
        }
        else
        {
            resultString = [NSMutableString stringWithFormat:@"%@%@",appendString,resultString];
        }
    }
    return resultString;
}

+ (NSString *)createSignatureWithParam:(NSDictionary*)param {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MMdd";
    NSString *time = [NSString stringWithFormat:@"aocao%@",[formatter stringFromDate:[NSDate date]]];
    NSString *signature = nil;
    NSArray *keyArray = [param allKeys];
    NSMutableString *paramsStirng = [[NSMutableString alloc] init];
    for (int x = 0; x<keyArray.count; x++) {
        [paramsStirng appendFormat:@"%@=%@",keyArray[x],param[keyArray[x]]];
    }
    [paramsStirng appendFormat:@"timestamp=%ld",(long)[[NSDate date] timeIntervalSince1970]];
    [paramsStirng appendFormat:@",%@",time];
    signature = [self md5:paramsStirng];
    return [signature uppercaseString];
}

+ (UIImage*)sacleImage:(UIImage*)tmpImage
{
    UIImage *uploadImage = nil;
    if (tmpImage.images.count > 0) {
        return tmpImage;
    }
    NSData * imageData = UIImageJPEGRepresentation(tmpImage, 0.5);
    NSUInteger sizeOriginKB = [imageData length]/1000;
    if (sizeOriginKB > 300)
    {
        float a = 300.00;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = tmpImage.size;
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [uploadImage drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        imageData = UIImagePNGRepresentation(smallImage);
    }
    
    uploadImage = [UIImage imageWithData:imageData];
    return uploadImage;
    
}



+ (void)showSubjectReportWithId:(NSInteger)InfoId
                      andUserId:(NSInteger)userId {
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *reasonAction1 = [UIAlertAction actionWithTitle:@"垃圾广告营销" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"垃圾广告营销\""];
    }];
    UIAlertAction *reasonAction2 = [UIAlertAction actionWithTitle:@"嘲讽/不友善内容" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"嘲讽/不友善内容\""];
    }];
    UIAlertAction *reasonAction3 = [UIAlertAction actionWithTitle:@"侮辱谩骂内容" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"侮辱谩骂内容\""];
    }];
    UIAlertAction *reasonAction4 = [UIAlertAction actionWithTitle:@"淫秽色情信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"淫秽色情信息\""];

    }];
    UIAlertAction *reasonAction5 = [UIAlertAction actionWithTitle:@"违法有害信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"违法有害信息\""];
    }];
    UIAlertAction *reasonAction6 = [UIAlertAction actionWithTitle:@"其他违法信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportSubjectWithId:InfoId andReason:@"\"其他违法信息\""];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [sheetController addAction:reasonAction1];
    [sheetController addAction:reasonAction2];
    [sheetController addAction:reasonAction3];
    [sheetController addAction:reasonAction4];
    [sheetController addAction:reasonAction5];
    [sheetController addAction:reasonAction6];
    [sheetController addAction:cancelAction];
    [[self keyController] presentViewController:sheetController
                                       animated:YES
                                     completion:nil];
}


+ (void)reportSubjectWithId:(NSInteger)InfoId
                  andReason:(NSString*)string {
//    NSDictionary *submitDic = @{@"InfoId":@(InfoId)};
//    
//    NSString *submitBody = string;
   [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO;
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow
                         animated:YES];
    [self showAAlertMessage:@"信息提交成功，感谢您的反馈"
                      title:@"温馨提示"
                buttonTexts:@[@"好的"]
               buttonAction:^(int buttonIndex)
    {
        
    }];
}

+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view
                                   fromColor:(UIColor *)fromColor
                                     toColor:(UIColor *)toColor{
    
    //    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)toColor.CGColor];
    
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);
    
    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];
    
    return gradientLayer;
}
@end
